package ru.housewife.service.userstables;

import org.hibernate.Session;
import ru.common.hibernate.HibernateAction;
import ru.housewife.form.UserForm;
import ru.housewife.form.UsersTableForm;
import ru.housewife.model.User;
import ru.housewife.model.UsersTable;

/**
 * saves new users table
 *
 * @author Alexander Troshanin
 */
public class AddNewUsersTable implements HibernateAction<UsersTable> {

    private UsersTableForm usersTableForm;

    public AddNewUsersTable(UsersTableForm usersTableForm) {
        this.usersTableForm = usersTableForm;
    }

    @Override
    public UsersTable execute(Session session) {
        UserForm userForm = usersTableForm.getUser();
        User user = (User) session.get(User.class, userForm.getId());
        if (user == null) {
            return null;
        }
        UsersTable usersTable = new UsersTable();
        usersTable.setUser(user);
        usersTable.setFrom(usersTableForm.getFrom());
        usersTable.setTo(usersTableForm.getTo());
        usersTable.setType(usersTableForm.getType());
        usersTable.setName(usersTableForm.getName());
        usersTable.setPeriodLength(usersTableForm.getPeriodLength());
        usersTable.setPermanent(usersTableForm.isPermanent());

        session.save(usersTable);
        usersTableForm.setId(usersTable.getId());
        userForm.addUsersTable(new UsersTableForm(userForm, usersTable));

        // todo: check whether it is necessary to add: user.getUsersTables().add(userTable); session.save(user);

        return usersTable;
    }
}
